#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIOT智能学习桌项目 - 语音识别集成版本
集成SpeechRecognition库的完整系统
支持语音控制、坐姿监测、数据记录等功能
"""

import speech_recognition as sr
import pyttsx3
import threading
import time
import random
import json
import os
from datetime import datetime, timedelta
import queue

class SmartDeskWithVoice:
    """集成语音识别的智能学习桌系统"""
    
    def __init__(self):
        """初始化智能学习桌系统"""
        print("🎯 初始化智能学习桌系统...")
        
        # 语音识别组件
        self.recognizer = sr.Recognizer()
        self.microphone = sr.Microphone()
        
        # 语音合成组件
        self.tts_engine = pyttsx3.init()
        self.tts_engine.setProperty('rate', 150)  # 语速
        self.tts_engine.setProperty('volume', 0.8)  # 音量
        
        # 系统状态
        self.is_running = False
        self.voice_recognition_active = False
        self.posture_monitoring_active = False
        
        # 坐姿监测数据
        self.current_distance = 35  # 当前距离(cm)
        self.ideal_distance_range = (30, 50)  # 理想距离范围
        self.posture_alerts = 0
        
        # 学习数据
        self.session_start_time = None
        self.total_study_time = 0
        self.focus_score = 85
        
        # 语音命令队列
        self.voice_queue = queue.Queue()
        
        # 调整麦克风
        self._setup_microphone()
        
        print("✅ 智能学习桌系统初始化完成")
    
    def _setup_microphone(self):
        """设置麦克风"""
        try:
            print("🔧 正在设置麦克风...")
            with self.microphone as source:
                self.recognizer.adjust_for_ambient_noise(source, duration=1)
                print(f"✅ 麦克风设置完成，噪音阈值: {self.recognizer.energy_threshold}")
        except Exception as e:
            print(f"⚠️ 麦克风设置失败: {e}")
    
    def speak(self, text):
        """语音播报"""
        print(f"🔊 语音播报: {text}")
        try:
            self.tts_engine.say(text)
            self.tts_engine.runAndWait()
        except Exception as e:
            print(f"❌ 语音播报失败: {e}")
    
    def listen_for_voice(self):
        """监听语音输入"""
        try:
            print("🎤 正在监听语音...")
            
            with self.microphone as source:
                # 监听音频，设置较短的超时时间
                audio = self.recognizer.listen(source, timeout=1, phrase_time_limit=5)
            
            print("🔄 正在识别语音...")
            
            # 使用Google语音识别
            text = self.recognizer.recognize_google(audio, language='zh-CN')
            
            print(f"🗣️ 识别结果: {text}")
            return text
            
        except sr.WaitTimeoutError:
            return None  # 超时，无语音输入
        except sr.UnknownValueError:
            print("❌ 无法识别语音内容")
            return None
        except sr.RequestError as e:
            print(f"❌ 语音识别服务错误: {e}")
            return None
        except Exception as e:
            print(f"❌ 语音识别出错: {e}")
            return None
    
    def process_voice_command(self, command):
        """处理语音命令"""
        if not command:
            return
        
        command = command.lower()
        
        # 问候命令
        if "你好" in command or "小助手" in command:
            response = "你好！我是智能学习桌助手，很高兴为您服务！"
            self.speak(response)
        
        # 时间查询
        elif "时间" in command or "几点" in command:
            current_time = datetime.now().strftime("%H点%M分")
            response = f"现在是{current_time}"
            self.speak(response)
        
        # 学习时长查询
        elif "学习时长" in command or "学了多久" in command:
            if self.session_start_time:
                elapsed = datetime.now() - self.session_start_time
                minutes = int(elapsed.total_seconds() / 60)
                response = f"您已经学习了{minutes}分钟"
            else:
                response = "学习会话尚未开始"
            self.speak(response)
        
        # 坐姿检查
        elif "坐姿" in command or "姿势" in command:
            if self.current_distance < self.ideal_distance_range[0]:
                response = "您坐得太近了，请往后坐一点"
            elif self.current_distance > self.ideal_distance_range[1]:
                response = "您坐得太远了，请往前坐一点"
            else:
                response = "您的坐姿很好，请保持"
            self.speak(response)
        
        # 专注度查询
        elif "专注度" in command or "专注" in command:
            response = f"您当前的专注度评分是{self.focus_score}分"
            self.speak(response)
        
        # 休息提醒
        elif "休息" in command:
            response = "好的，建议您休息10分钟，做做眼保健操"
            self.speak(response)
        
        # 开始学习
        elif "开始学习" in command:
            self.start_study_session()
            response = "学习模式已启动，祝您学习愉快！"
            self.speak(response)
        
        # 结束学习
        elif "结束学习" in command:
            self.end_study_session()
            response = "学习会话已结束，感谢您的努力！"
            self.speak(response)
        
        # 帮助命令
        elif "帮助" in command or "功能" in command:
            response = "我可以帮您查看时间、学习时长、坐姿检查、专注度评分等功能"
            self.speak(response)
        
        # 停止命令
        elif "停止" in command or "退出" in command:
            response = "好的，系统即将关闭"
            self.speak(response)
            self.is_running = False
        
        else:
            response = "抱歉，我没有理解您的命令，请说帮助查看可用功能"
            self.speak(response)
    
    def simulate_posture_monitoring(self):
        """模拟坐姿监测"""
        while self.posture_monitoring_active:
            # 模拟距离变化
            self.current_distance = random.randint(15, 65)
            
            # 检查坐姿
            if (self.current_distance < self.ideal_distance_range[0] or 
                self.current_distance > self.ideal_distance_range[1]):
                
                self.posture_alerts += 1
                
                # 坐姿警报
                if self.current_distance < self.ideal_distance_range[0]:
                    alert_msg = f"⚠️ 坐姿警报：距离过近 ({self.current_distance}cm)"
                    voice_msg = "请注意坐姿，您坐得太近了"
                else:
                    alert_msg = f"⚠️ 坐姿警报：距离过远 ({self.current_distance}cm)"
                    voice_msg = "请注意坐姿，您坐得太远了"
                
                print(alert_msg)
                
                # 语音提醒（每5次警报提醒一次，避免过于频繁）
                if self.posture_alerts % 5 == 0:
                    threading.Thread(target=self.speak, args=(voice_msg,), daemon=True).start()
            
            time.sleep(3)  # 每3秒检查一次
    
    def voice_recognition_loop(self):
        """语音识别循环"""
        while self.voice_recognition_active:
            try:
                # 监听语音
                command = self.listen_for_voice()
                
                if command:
                    # 处理语音命令
                    self.process_voice_command(command)
                
                time.sleep(0.5)  # 短暂休息
                
            except Exception as e:
                print(f"❌ 语音识别循环出错: {e}")
                time.sleep(1)
    
    def start_study_session(self):
        """开始学习会话"""
        self.session_start_time = datetime.now()
        self.posture_alerts = 0
        self.focus_score = 85
        
        print("📚 学习会话已开始")
        print(f"⏰ 开始时间: {self.session_start_time.strftime('%H:%M:%S')}")
    
    def end_study_session(self):
        """结束学习会话"""
        if self.session_start_time:
            end_time = datetime.now()
            session_duration = end_time - self.session_start_time
            minutes = int(session_duration.total_seconds() / 60)
            
            # 更新总学习时间
            self.total_study_time += minutes
            
            # 计算专注度评分
            if self.posture_alerts > 0:
                self.focus_score = max(60, 100 - (self.posture_alerts * 2))
            
            print("\n📊 学习会话总结:")
            print(f"⏰ 学习时长: {minutes}分钟")
            print(f"⚠️ 坐姿提醒: {self.posture_alerts}次")
            print(f"🎯 专注度评分: {self.focus_score}分")
            print(f"📈 累计学习时间: {self.total_study_time}分钟")
            
            self.session_start_time = None
    
    def display_status(self):
        """显示系统状态"""
        current_time = datetime.now().strftime("%H:%M:%S")
        
        print(f"\n🖥️ 智能学习桌状态 [{current_time}]")
        print("="*50)
        print(f"🎤 语音识别: {'🟢 启用' if self.voice_recognition_active else '🔴 禁用'}")
        print(f"📏 当前距离: {self.current_distance}cm")
        print(f"🎯 理想范围: {self.ideal_distance_range[0]}-{self.ideal_distance_range[1]}cm")
        print(f"⚠️ 坐姿警报: {self.posture_alerts}次")
        print(f"🎯 专注度: {self.focus_score}分")
        
        if self.session_start_time:
            elapsed = datetime.now() - self.session_start_time
            minutes = int(elapsed.total_seconds() / 60)
            print(f"📚 当前学习时长: {minutes}分钟")
        else:
            print("📚 学习状态: 未开始")
        
        print(f"📊 累计学习时间: {self.total_study_time}分钟")
        print("="*50)
    
    def run(self):
        """运行智能学习桌系统"""
        print("\n🚀 启动智能学习桌系统")
        print("="*60)
        
        self.is_running = True
        self.voice_recognition_active = True
        self.posture_monitoring_active = True
        
        # 启动语音识别线程
        voice_thread = threading.Thread(
            target=self.voice_recognition_loop,
            daemon=True
        )
        voice_thread.start()
        
        # 启动坐姿监测线程
        posture_thread = threading.Thread(
            target=self.simulate_posture_monitoring,
            daemon=True
        )
        posture_thread.start()
        
        # 欢迎语音
        self.speak("智能学习桌系统已启动，请说你好开始使用")
        
        print("\n💡 语音命令示例:")
        print("   - 你好 / 小助手")
        print("   - 现在几点 / 时间")
        print("   - 开始学习 / 结束学习")
        print("   - 学习时长 / 专注度")
        print("   - 坐姿检查 / 休息")
        print("   - 帮助 / 停止")
        
        print("\n🎤 语音识别已启动，请开始说话...")
        print("⌨️ 按 'q' 键退出系统")
        print("="*60)
        
        try:
            # 主循环
            while self.is_running:
                # 显示系统状态
                self.display_status()
                
                # 检查键盘输入
                import select
                import sys
                
                if sys.stdin in select.select([sys.stdin], [], [], 0.1)[0]:
                    key = sys.stdin.readline().strip()
                    if key.lower() == 'q':
                        print("🛑 用户请求退出")
                        break
                
                time.sleep(5)  # 每5秒更新一次状态
                
        except KeyboardInterrupt:
            print("\n⏹️ 用户中断程序")
        except Exception as e:
            print(f"❌ 系统运行出错: {e}")
        finally:
            # 清理资源
            self.is_running = False
            self.voice_recognition_active = False
            self.posture_monitoring_active = False
            
            # 如果有学习会话，结束它
            if self.session_start_time:
                self.end_study_session()
            
            self.speak("系统已关闭，感谢使用")
            print("✅ 智能学习桌系统已关闭")

def main():
    """主函数"""
    print("🎯 AIOT智能学习桌 - 语音识别集成版")
    print("="*60)
    
    # 检查依赖
    try:
        import speech_recognition as sr
        import pyttsx3
        print("✅ 语音识别库检查通过")
    except ImportError as e:
        print(f"❌ 缺少依赖库: {e}")
        print("💡 请运行: pip install SpeechRecognition pyaudio pyttsx3")
        return
    
    # 创建并运行智能学习桌系统
    desk = SmartDeskWithVoice()
    desk.run()

if __name__ == "__main__":
    main() 